package com.mall.b2c.util;

import static com.mall.b2c.Constants.PRINCIPAL_SESSION_NAME;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import com.mall.b2c.domain.member.MemberDomain;
import com.mall.b2c.service.MemberService;
import com.mall.common.bean.Principal;
import com.mall.common.bean.User;
import com.mall.common.util.AppContext;
import com.mall.common.util.SpringUtils;

/**
 * 提供一些系统中使用到的共用方法
 * 比如获得当前用户信息
 * @author zhenglong
 */
public class ShopUtil {

	/**
	 * 获得用户
	 * @param request
	 * @return
	 */
	public static User getUser() {
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		if (authentication == null) {
			return null;
		}
		Object principal = authentication.getPrincipal();
		if (principal == null || !(principal instanceof User)) {
			return null;
		} else {
			return (User) principal;
		}
	}
	
	/**
	 * 获得用户ID
	 * 
	 * @param request
	 * @return
	 */
	public static Long getUserId() {
		User user = getUser();
		if (user != null) {
			return user.getId();
		} else {
			return null;
		}
	}
	/**
	 * 获取当前会员
	 */
	public static Principal getPrincipal(){
		Principal principal = (Principal)AppContext.getSessionAttr(PRINCIPAL_SESSION_NAME);
		return principal;
	}
	
	/**
	 * 获取当前会员ID
	 */
	public static Long getMemberId(){
		Principal principal = (Principal)AppContext.getSessionAttr(PRINCIPAL_SESSION_NAME);
		if(principal == null){
			return null;
		}
		return principal.getId();
	}
	
	/**
	 * 获取当前会员用户名
	 */
	public static String getMemberName(){
		Principal principal = (Principal)AppContext.getSessionAttr(PRINCIPAL_SESSION_NAME);
		if(principal == null){
			return null;
		}
		return principal.getUsername();
	}

	// 获取当前登录会员，若未登录则返回null
	public static MemberDomain getMember() {
		Long id = getMemberId();
		if (id == null) {
			return null;
		}
		MemberService memberService = (MemberService)SpringUtils.getBean("memberServiceImpl");
		MemberDomain loginMember = (MemberDomain)memberService.find(id);
		return loginMember;
	}
}
